package com.huanzhidadi.single.threadlocal;

import org.springframework.util.StopWatch;

public class ThreadLocalTest {

    private ThreadLocal<String> threadLocal = new ThreadLocal<>();

    public String getContent() {
        return threadLocal.get();
    }

    public void setContent(String content) {
        this.threadLocal.set(content);
    }

    public static void main(String[] args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("ThreadLocal方式");
        ThreadLocalTest threadLocalTest = new ThreadLocalTest();
        for (int i=0; i<6; i++) {
            new Thread(() -> {
                // ThreadLocal采用以空间换时间的概念，为每个线程都提供一份变量副本，从而实现同时访问而互不干扰
                threadLocalTest.setContent(Thread.currentThread().getName() + " 的数据");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "\t  " + threadLocalTest.getContent());
            }, String.valueOf(i)).start();
        }
        // 所有线程累加完成后输出 如果除了主线程外还有子线程存在，则主线程让出执行时间
        while (Thread.activeCount() > 2) Thread.yield();
        stopWatch.stop();
        System.out.println(stopWatch.getTotalTimeMillis() + "ms");
    }
}
